package dao.impl;

import dao.RecordDao;
import po.Record;
import util.BaseDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RecordDaoImpl implements RecordDao {
    @Override
    public List<Record> selectRecords() {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        List<Record> list = new ArrayList<>();
        try {
            // 1.连接数据库
            con = BaseDao.getConnection();
            // 2.预编译
            String sql = "select * from record";
            ps = con.prepareStatement(sql);
            // 3.执行sql
            rs = ps.executeQuery();
            while (rs.next()){
                Record record = new Record();
                record.setGoodId(rs.getString("good_id"));
                record.setGoodName(rs.getString("good_name"));
                record.setType(rs.getString("type"));
                record.setCount(rs.getInt("count"));
                record.setCost(rs.getDouble("cost"));
                record.setShipper((rs.getString("shipper")));
                record.setWarehouseId(rs.getString("warehouse_id"));
                record.setExStorage(rs.getDate("ex_storage"));

                list.add(record);
            }

            return list;
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(con,ps,rs);
        }
        return null;
    }

    @Override
    public void addRecord(Record record) {
        String sql = "insert into record values (?,?,?,?,?,?,?,now())";
        List<Object> list = new ArrayList<>();
        list.add(record.getGoodId());
        list.add(record.getGoodName());
        list.add(record.getType());
        list.add(record.getCount());
        list.add((record.getCost()));
        list.add((record.getShipper()));
        list.add(record.getWarehouseId());

        BaseDao.addUpdateDelete(sql, list.toArray());
    }
}
